package Demo;

import com.google.gson.Gson;

import java.util.HashMap;

//"studentid":001,"name":"zhang","score":98,"hobby":"代码","clazz":"一班"
public class jsonDemo {
    public static void main(String[] args) {
        String jsonstr="{\"studentid\":001,\"name\":\"zhang\",\"score\":98,\"hobby\":\"敲代码\",\"clazz\":\"一班\"}";
        System.out.println(jsonstr);

        Gson gson = new Gson();
        //json转化为对象

        //转化为hashmap对象
        HashMap hashMap = gson.fromJson(jsonstr, HashMap.class);
        System.out.println(hashMap);

        //转化为Student类对象
        //注意Student类里面的变量个数与名字要和json里面相对应
        //比如我将Student里的hobby成员变量改为gender，结果就会变成
        //Student{studentid=1, name='zhang', score=98, gender='null', clazz='一班'}
        System.out.println("----------------");
        Student stu = gson.fromJson(jsonstr, Student.class);
        System.out.println(stu.toString());
        //通过student类里面的方法，获取单个属性值
        System.out.println(stu.getHobby());
        System.out.println("----------------");

        System.out.println("hello");

        //对象转化为json
        String s = gson.toJson(stu);
        System.out.println(s);

        //对象应该是key——value格式，如果不是则无法转换，但是不会报错，会原样输出
        String[] strings = {"a","b","c","d","e"};
        String s1 = gson.toJson(strings);
        System.out.println(s1);


    }
}
